
// const formatTime = dateTimeStamp => {
//   let date = new Date(dateTimeStamp)
//   const year = date.getFullYear()
//   const month = date.getMonth() + 1
//   const day = date.getDate()
//   const hour = date.getHours()
//   const minute = date.getMinutes()
//   const second = date.getSeconds()

//   return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
// }
function formatTime(number, format) {
  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];
  var date = new Date(number * 1000);
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));
 
  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));
 
  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
}
// 格式化的时间转成时间戳
const dateStr2timestamp = (dateStr) => {
  return (typeof dateStr === 'string') 
  ? 
  Date.parse(new Date(dateStr)) 
  : 
  Date.parse(new Date())
}
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
const addZero = (i) => {
  i = typeof i === 'string' ? Number(i) : i;
  return i < 10 ? "0" + i : "" + i;
}
const H5key='O2018@(*cbctcbct*)@8102O'
/*
* 合并数组
*/
const SplitArray = function (list, sp) {
  if (typeof list != 'object') return [];
  if (sp === undefined) sp = [];
  for (var i = 0; i < list.length; i++) {
      sp.push(list[i]);
  }
  return sp;
}
// 获取周几
function fun_week(datestr){
  var weekArray = new Array("周日", "周一", "周二", "周三", "周四", "周五", "周六");
  var week = weekArray[new Date(datestr).getDay()];
  return week;
}
// 时间按多长时间之前的格式展示
const timeAgo = function (dateTimeStamp) {
  dateTimeStamp = Number(dateTimeStamp) * 1000
  let result = "";
  let minute = 1000 * 60;      //把分，时，天，周，半个月，一个月用毫秒表示
  let hour = minute * 60;
  let day = hour * 24;
  let week = day * 7;
  let halfamonth = day * 15;
  let month = day * 30;
  let now = new Date().getTime();   //获取当前时间毫秒
  let timestamp = new Date(dateTimeStamp).getTime();
  let diffValue = now - timestamp;//时间差
  if (diffValue < 0) {
    return result;
  }
  let minC = diffValue / minute;  //计算时间差的分，时，天，周，月
  let hourC = diffValue / hour;
  let dayC = diffValue / day;
  let weekC = diffValue / week;
  let monthC = diffValue / month;
  let oneDay = 1000*60*60*24
  // 今天
  let Today = new Date(dateTimeStamp).toDateString() == new Date().toDateString()
  // 昨天
  let yesterday = new Date(dateTimeStamp + oneDay).toDateString() == new Date().toDateString()
  // 前天
  let beforeYesterday = new Date(dateTimeStamp + oneDay*2).toDateString() == new Date().toDateString()
  //格式化日期
  let date = new Date(dateTimeStamp)
  let y = date.getFullYear()
  let m = date.getMonth() + 1
  m = m < 10 ? ('0' + m) : m
  let d = date.getDate()
  d = d < 10 ? ('0' + d) : d
  let h = date.getHours()
  h = h < 10 ? ('0' + h) : h
  let mm = date.getMinutes()
  let ss = date.getSeconds()
  mm = mm < 10 ? ('0' + mm) : mm
  ss = ss < 10 ? ('0' + ss) : ss
  if (diffValue >= 0 && diffValue <= minute) {
    result = "刚刚"
  } else if (minC >= 1 && minC <= 59) {
    result = " " + parseInt(minC) + "分钟前"
  }else if (Today) { //今天
    result = `${h}:${mm}`
  } else if (yesterday) { // 昨天
    result = `昨天 ${h}:${mm}`
  } else if (beforeYesterday) { // 前天
    result = `前天 ${h}:${mm}`
  } else if (weekC <=1) { //一周内
    result = `${fun_week(dateTimeStamp)} ${h}:${mm}`
  } else { // 一周前
    result = `${y}-${m}-${d} ${h}:${mm}`
  }
  return result;
}
const $await = function(promise){
  return promise.then(res => {
    if (res.data && res.data.c === 200) { // 成功
      return [null, res.data.d]
    } else if(res.data.c === 483){// 未登录
      getUrl()
      wx.navigateTo({
        url: '/pages/login/login',
        success: (result)=>{
          
        },
        fail: ()=>{},
        complete: ()=>{}
      });
      return [res,null]
    } else { // 其他异常
      wx.showToast({
        icon:'none',
        title: res.data.m,
        duration: 2000
      })
      return [res, null]
    }
  }).catch(err => {
    wx.showToast({
      icon:'none',
      title: '服务器开小差',
      duration: 2000
    })
    return [err, null]
  })
}
const getUrl = ()=> {  
  var pages = getCurrentPages() //获取加载的页面  
  var currentPage = pages[pages.length - 1] //获取上一个页面对象  
  var url = currentPage.route //当前页面url  
  wx.setStorageSync('Router', `${url}`)  
  var options = currentPage.options //如果要获取url中所带的参数可以查看options  
  //参数多时通过&拼接url的参数  
  if(options){
      var urlWithArgs = url + '?'  
      for (var key in options) {  
      var value = options[key]  
      urlWithArgs += key + '=' + value + '&'  
      }  
      urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1) 
      wx.setStorageSync('Router', `${urlWithArgs}`)  
  }
}
// value 数值 bit 位数 unit （k/w）
const toFix = function (value,bit,unit) {
  if (value >= bit) { //字数是否过千
    var sen= value/bit;//过千处理
    var num = sen.toFixed(1)//保留一位小数
    return num + unit//字符串拼接
  } else {
    return value
  }
}
// 格式化视频时长  格式 00:00
const formatSeconds = function(value) {
  if (value == undefined) {
    value = 0;
  }
  var second = parseInt(value); // 秒
  var min = 0; // 分
  var hour = 0; // 小时
  if (second > 60) {
    min = parseInt(second / 60);
    second = parseInt(second % 60);
    if (min > 60) {
      hour = parseInt(min / 60);
      min = parseInt(min % 60);
    }
  }
  
  var result = "";
  // if (hour > 0) {
  //   hour = addZero(parseInt(hour));
  //   result = hour + ":";
  // }
  if (min > 0) {
    min = addZero(parseInt(min));
    result = min + ":";
  }else{
    result = "00:";
  }
  if(second > 0){
    second = addZero(parseInt(second));
    result = result + second;
  }else{
    result = result + '00';
  }
  return result;
}
/**
     * @desc 函数防抖
     * @param func 函数
     * @param wait 延迟执行毫秒数
     * @param immediate true 表立即执行，false 表非立即执行
     */
 const Debounce = (func, wait, immediate) => {
  let timeout
  wait = wait || 500
  immediate = immediate || true

  return function() {
    const context = this
    const args = arguments

    if (timeout) clearTimeout(timeout)
    if (immediate) {
      var callNow = !timeout
      timeout = setTimeout(() => {
        timeout = null
      }, wait)
      if (callNow) func.apply(context, args)
    } else {
      timeout = setTimeout(function() {
        func.apply(context, args)
      }, wait)
    }
  }
}

/**
   * 函数节流
   * @param fn
   * @param interval
   * @returns {Function}
   * @constructor
   */
const Throttle = (fn, t) => {
  let last
  let timer
  const interval = t || 500
  return function() {
    const args = arguments
    const now = +new Date()
    if (last && now - last < interval) {
      clearTimeout(timer)
      timer = setTimeout(() => {
        last = now
        // console.log("实际执行函数（" + interval + "）：" + typeof fn)
        fn.apply(this, args)
      }, interval)
    } else {
      last = now
      // console.log("实际执行函数（" + interval + "）：" + typeof fn)
      fn.apply(this, args)
    }
  }
}
module.exports = {
  dateStr2timestamp,
  formatTime,
  H5key,
  addZero,
  SplitArray,
  $await,
  timeAgo,
  toFix,
  formatSeconds,
  Debounce,
  Throttle
}
